import datetime
import os
import re
import openpyxl
from config import OUTPUT_DIRS_DEFAULT


def read_data_from_txt(file_path):
    apis = []
    with open(file_path, encoding='UTF-8', errors='ignore') as f:
        lines = f.readlines()
        for line in lines:
            if line.startswith('    ') and not line.lstrip().startswith('#'):
                pattern = re.compile(r'(.*)?;.*')
                api = re.match(pattern, line.strip())
                apis.append(api.group(1))
    return apis

def get_apis_from_musl(musl_file_path):
    apis = []
    try:
        wb = openpyxl.load_workbook(musl_file_path)
    except:
        print(f'load ndk file {excel_file} failed')

    sheet = wb['musl-posix']
    max_row = sheet.max_row
    for row in range(2, max_row+1):
        api = sheet.cell(row, 4).value
        apis.append(api)
    print(apis)
    return apis

def compareWithMusl(apis_libc, apis_musl):
    diff_List = []
    for api in apis_libc:
        print(api)
        if api not in apis_musl:
            diff_List.append(api)
    build_file(diff_List)

def build_file(apis, save_file=None):
    time_now = datetime.datetime.now()
    date_time = "%s-%s-%s" % (time_now.year, time_now.month, time_now.day)
    if not save_file:
        if not (os.path.exists(OUTPUT_DIRS_DEFAULT)):
            os.mkdir(OUTPUT_DIRS_DEFAULT)
        work_dir = os.path.join(OUTPUT_DIRS_DEFAULT, date_time)
        if not (os.path.exists(work_dir)):
            os.mkdir(work_dir)
        save_file = os.path.join(work_dir, "musl_libc_compare.txt")
    file = open(save_file, 'w')
    for api in apis:
        file.writelines(api+'\n')
    return

if __name__ == '__main__':
    apis_libc = read_data_from_txt('./data/libc.map.txt')
    apis_musl = get_apis_from_musl('./data/musl_compatibility.xlsx')
    compareWithMusl(apis_libc, apis_musl)